import { uniShowToast, uniShowLoading, uniHideLoading, uniGetStorageSync, uniShowModal } from '@/utils/index.js';
// import { commonStore } from '@/stores/common';
import packageJson from '../../../package.json';
import { ResultEnum } from '@/enums/ResultEnum';
//请求url处理
const requesUrl = (url: any) => {
	/* #ifdef APP-PLUS */
	return url.includes('http') ? url : 'http://yh.zhiqiyanlv.com' + url;
	/* #endif */
	/* #ifdef H5 */
	return url.includes('http') ? url : import.meta.env.VITE_APP_BASE_API + url;
	/* #endif */
};

/**
 * 异常拦截处理器
 *
 * @param {*} error
 */
const errorHandler = (error: any) => {
	if (error.response) {
		if (error.response.status == 401) {
			// removeAll();
			location.reload();
		} else if (error.response.status == 403) {
			uniShowToast('没有权限！');
		} else {
			uniShowToast('网络异常，请稍候再试！');
		}
	}
};

// 请求拦截器
const requestHeader = (data: any) => {
	const user = uniGetStorageSync('user') || {};
	const token = user ? user.token : '';
	const auth = uniGetStorageSync('auth') || {};
	const accessToken = auth.accessToken;
	return {
		accessToken: accessToken,
		token: token,
		role: data.role_id ? data.role_id : user.role,
		teamid: data.team_id ? data.team_id : user.now_team_id,
		devicetype: 'app',
		version: packageJson.version
	};
};

// 响应拦截器
const requestResponse = (res: any) => {
	// if (commonStore().isMsg) {
	// 	setTimeout(() => {
	// 		commonStore().isMsg = false;
	// 	}, 5000);
	// 	return false;
	// }

	const { code, msg } = res;
	if (code !== ResultEnum.SUCCESS) {
		if (code === ResultEnum.TOKEN_INVALID) {
			// commonStore().isMsg = true;
			uni.removeStorageSync('auth');
			if (uni.sendNativeEvent) {
				uniShowModal('温馨提示', '第三方系统登录失效，请退出应用后重新进入', (e: any) => {
					uni.sendNativeEvent('closeMe', { delay: 1 }, (res) => {
						console.log('closeMe----' + JSON.stringify(res));
					});
				});
			}
			return false;
		} else {
			uniShowToast(msg || '系统出错');
			return false;
		}
	}
	return true;
};

/**
 * GET 请求
 *
 * @param {String} url
 * @param {Object} data
 * @param {Object} options
 * @returns {Promise<any>}
 */
export const get = (url: any, data = {}, options = { loading: false }) => {
	if (options.loading) {
		uniShowLoading();
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: requesUrl(url),
			method: 'GET',
			header: requestHeader(data),
			data: data,
			...options,
			success: (res) => {
				if (requestResponse(res.data)) {
					resolve(res.data); // 如果请求成功，打印返回的数据
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				errorHandler(err); // 如果请求失败，打印错误信息
				reject(err);
			},
			complete: () => {
				if (options.loading) {
					uniHideLoading();
				}
			}
		});
	});
};

/**
 * POST 请求
 *
 * @param {String} url
 * @param {Object} data
 * @param {Object} options
 * @returns {Promise<any>}
 */
export const post = (url: any, data = {}, options = { loading: false }) => {
	if (options.loading) {
		uniShowLoading();
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: requesUrl(url),
			method: 'POST',
			header: requestHeader(data),
			data: data,
			...options,
			success: (res) => {
				if (requestResponse(res.data)) {
					resolve(res.data); // 如果请求成功，打印返回的数据
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				errorHandler(err); // 如果请求失败，打印错误信息
				reject(err);
			},
			complete: () => {
				if (options.loading) {
					uniHideLoading();
				}
			}
		});
	});
};

/**
 * 上传文件 POST 请求
 *
 * @param {String} url
 * @param {Object} data
 * @param {Object} options
 * @returns {Promise<any>}
 */
export const upload = (url: any, data: any, options: any = { loading: false }) => {
	if (options.loading) {
		uniShowLoading();
	}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: requesUrl(url), //仅为示例，非真实的接口地址
			filePath: data.filePath,
			name: 'file',
			header: requestHeader(data),
			...options,
			success: (res) => {
				if (requestResponse(res.data)) {
					resolve(res.data); // 如果请求成功，打印返回的数据
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				errorHandler(err); // 如果请求失败，打印错误信息
				reject(err);
			},
			complete: () => {
				if (options.loading) {
					uniHideLoading();
				}
			}
		});
	});
};
/**
 * 上传文件 DELETE 请求
 *
 * @param {String} url
 * @param {Object} data
 * @param {Object} options
 * @returns {Promise<any>}
 */
export const deleteRequest = (url: any, data = {}, options = { loading: true }) => {
	if (options.loading) {
		uniShowLoading();
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: requesUrl(url),
			method: 'DELETE',
			header: requestHeader(data),
			data: data,
			...options,
			success: (res) => {
				if (requestResponse(res.data)) {
					resolve(res.data); // 如果请求成功，打印返回的数据
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				errorHandler(err); // 如果请求失败，打印错误信息
				reject(err);
			},
			complete: () => {
				if (options.loading) {
					uniHideLoading();
				}
			}
		});
	});
};
/**
 * 上传文件 put 请求
 *
 * @param {String} url
 * @param {Object} data
 * @param {Object} options
 * @returns {Promise<any>}
 */
export const put = (url: any, data = {}, options = { loading: false }) => {
	if (options.loading) {
		uniShowLoading();
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: requesUrl(url),
			method: 'PUT',
			header: requestHeader(data),
			data: data,
			...options,
			success: (res) => {
				if (requestResponse(res.data)) {
					resolve(res.data); // 如果请求成功，打印返回的数据
				} else {
					reject(res);
				}
			},
			fail: (err) => {
				errorHandler(err); // 如果请求失败，打印错误信息
				reject(err);
			},
			complete: () => {
				if (options.loading) {
					uniHideLoading();
				}
			}
		});
	});
};
